<?php if(!defined('IN_FIRADIO')) {header('HTTP/1.1 403 Forbidden');exit('<h1>Access Denied</h1>');}?>
<?php $GLOBALS['script'][] = function() {?><script>
const cache = {};
cache.process_status = 0;
cache.splitSize = 1024 * 1024 * 4;
cache.count_skip = [0, 0, 0, 0];
cache.count_added = 0;
cache.dbhost = 180;
cache.dbchar = 'a';
cache.isDebug = 0;
cache.postToServer = 1;
// cache.sList = ['----', ':'];
cache.sList = ['----'];
//cache.sList = [':'];
vue.data.api_upload_list = {};
vue.data.api_upload_list.rows = [];
vue.methods.formatSeconds = formatSeconds;
vue.mounted = function () {

};
/**
 * 格式化秒
 * @param int  value 总秒数
 * @return string result 格式化后的字符串
 */
function formatSeconds(value) {
    var theTime = parseInt(value); // 需要转换的时间秒
    var theTime1 = 0; // 分
    var theTime2 = 0; // 小时
    var theTime3 = 0; // 天
    if (theTime > 60) {
        theTime1 = parseInt(theTime / 60);
        theTime = parseInt(theTime % 60);
        if (theTime1 > 60) {
            theTime2 = parseInt(theTime1 / 60);
            theTime1 = parseInt(theTime1 % 60);
            if (theTime2 > 24) {//大于24小时
                theTime3 = parseInt(theTime2 / 24);
                theTime2 = parseInt(theTime2 % 24);
            }
        }
    }
    var result = '';
    if (theTime > 0) result = "" + parseInt(theTime) + "秒";
    if (theTime1 > 0) result = "" + parseInt(theTime1) + "分" + result;
    if (theTime2 > 0) result = "" + parseInt(theTime2) + "小时" + result;
    if (theTime3 > 0) result = "" + parseInt(theTime3) + "天" + result;
    return result;
}
</script><?php }?>

<div class="row">
    <div class="col-md-12">

                    <div class="box box-info">
                        <div class="box-header with-border">
                            <h3 class="box-title">Email账号上传</h3>
                        </div>
                        <!-- /.box-header -->
                        <!-- form start -->
                        <form id="form1" class="form-horizontal" onsubmit="return false;">
                            <div class="box-body">
                                <div class="form-group">
                                    <label for="file1" class="col-sm-2 control-label">选择要传的TXT文件</label>
                                    <div class="col-sm-10">
                                        <input type="file" id="file1" />
                                    </div>
                                    <div class="col-sm-10">
                                        <span id="span_L1"></span><br />
                                        <span id="span_L2"></span><br />
                                        <span id="span_L3"></span><br />
                                        <span id="span_L4"></span><br />
                                        <span id="span_L5"></span><br />
                                    </div>
                                </div>
                            </div>
                            <!-- /.box-body -->
                            <div class="box-footer">
                                <span class="pull-right" id="span_alert" style="color:red">请先选择要传的文件</span>
                                <button class="btn btn-info pull-right" id="button_start" style="display: none;">开始上传</button>
                                <button class="btn btn-warning pull-right" id="button_pause" style="display: none;">暂停上传</button>
                            </div>
                            <!-- /.box-footer -->
                        </form>
                    </div>


    </div>
  <!-- /.col -->
    <div class="col-md-6">

    </div>
</div>
<?php $GLOBALS['script'][] = function() {?><script>
function readAsText(file, start, length, _callback, _error) {
    const splitSign = "\r\n";
    const SIZE = file.size;
    if (start >= SIZE) {
        return _callback();
    }
    const fileReader = new FileReader();
    fileReader.onload = function() {
        const i = fileReader.result.lastIndexOf(splitSign);
        if (i === -1) return _error('没有找到指定的splitSign');
        const result = fileReader.result.substring(0, i);
        return _callback(result, start + i + splitSign.length);
    };
    return fileReader.readAsBinaryString(file.slice(start, start + length));
}
function readLine(text, arrLine) {
    const arr = text.split("\r\n");
    for (var i in arr) {
        const line = arr[i];
        if (line.length === 0) continue;
        const cols = getLine(line);
        const email = format_email(cols[0]);
        if (email === null) {
            cache.count_invaild++;
            if (cache.isDebug) console.log('无效Email：' + line);
            continue;
        }
        const password = format_password(cols[1]);
        if (password === null) {
            cache.count_invaild++;
            if (cache.isDebug) console.log('无效密码：' + line);
            continue;
        }
        arrLine.push([email, password]);
        if (cache.isDebug >= 2) console.log('[' + line.length + ']' + [email, password]);
    }
}
function getLine(line) {
    for (var k in cache.sList) {
        const sign = cache.sList[k];
        const i = line.indexOf(sign);
        if (i >= 0) {
            const email = line.substr(0, i);
            const password = line.substr(i + sign.length);
            return [email, password];
        }
    }
    return ['', ''];
}
function format_email(str) {
    return str;
    const patt1 = /[\dA-Z\-\_\.]{1,30}@([\dA-Z\-]{1,20}\.){1,10}([A-Z]{2,10})+/i;
    const ret = patt1.exec(str);
    if (ret === null) return null;
    return ret[0];
}
function format_password(str) {
    if (str == '') return null;
    return str;
}
function upload_start(fileOne, start) {
    // console.log('start=' + start);
    cache.time_start2 = +new Date();
    span_L2.innerHTML = '已处理: ' + format_mb(start) + ' MB (' + format_number(start / cache.file_size * 100, 1) + '%)';
    span_L2.innerHTML += ' 耗时: ' + format_number(((+new Date()) - cache.time_start1) / 1000, 1) + ' 秒';
    return readAsText(fileOne, start, cache.splitSize, function(text, endpos) {
        if (typeof(text) !== 'string' || text.length === 0) {
            var msg = '处理完毕！';
            msg += "\r\n";
            msg += '有效数量 ' + cache.count_vaild + ' 条' + "\r\n";
            msg += '新增队列 ' + cache.count_added + ' 条' + "\r\n";
            msg += "\r\n";
            msg += '耗时:' + ((+new Date()) - cache.time_start1) + 'ms';
            alert(msg);
            setStatus(0);
            return;
        }
        const arrLine = [];
        readLine(text, arrLine);
        upload_tosrv([arrLine, start, endpos], function (resData) {
            // 服务器上传成功后，记录下次开始的位置
            const speed = 1000 * cache.splitSize / ((+new Date()) - cache.time_start2);
            span_L4.innerHTML = '速度: ' + format_mb(speed) + ' MB/秒';
            span_L4.innerHTML += ' 预计还需要 ' + Math.floor((cache.file_size - start) / speed) + ' 秒完成';
            span_L5.innerHTML = '';
            if (resData !== undefined) {
                if (resData.count_skip) {
                    cache.count_skip[1] += resData.count_skip[1];
                    cache.count_skip[2] += resData.count_skip[2];
                    cache.count_skip[3] += resData.count_skip[3];
                    span_L5.innerHTML += '已跳队列:' + cache.count_skip[1] + '&nbsp;';
                    span_L5.innerHTML += '&nbsp;已跳错误:' + cache.count_skip[2] + '&nbsp;';
                    span_L5.innerHTML += '&nbsp;已跳成功:' + cache.count_skip[3] + '&nbsp;';
                }
                cache.count_added += resData.count_added;
                span_L5.innerHTML += '&nbsp;新增队列:' + cache.count_added + '';
            }
            window.localStorage[cache.uploadPosName] = endpos;
            if (cache.process_status === 1) {
                upload_start(fileOne, endpos);
            }
        });
        return;
    }, function (_error) {
        setStatus(0);
        alert(_error);
    });
}
function upload_tosrv(data, _callback) {
    cache.count_vaild += data[0].length;
    span_L3.innerHTML = '有效: ' + cache.count_vaild + ' 无效: ' + cache.count_invaild + ' 总共: ' + (cache.count_vaild + cache.count_invaild) + '';
    if (!cache.postToServer) {
        return _callback();
    }
    const form = {};
    form.dbhost = cache.dbhost;
    form.dbchar = cache.dbchar;
    form.upload_id = cache.upload_id;
    form.filename = cache.filename;
    form.cols = data[0];
    form.pos_start = data[1];
    form.pos_end = data[2];
    vue.methods.ApiPost('/panel/email/account_upload', form).then(function (res) {
        // 提交成功就继续
        return _callback(res.data);
    }, function (res) {
        // 发生错误时
        setStatus(0);
    }).then(function (res) {
    }).catch(function (reason) {
        console.log('catch:', reason);
    });
}
function addPreZero(num, len) {
    return ('000000000' + num).slice(-len);
}
function format_number(number, i) {
    const str = '' + Math.floor(number * Math.pow(10, i));
    const zhengshu = (str.length <= i) ? '0' : str.substring(0, str.length - i);
    return zhengshu + '.' + addPreZero(str.substr(-i), i);
}
function format_mb(iByte) {
    return format_number(iByte / 1024 / 1024, 2);
}
function setStatus(status) {
    if (status === -1) {
        jQuery('#button_pause').hide();
        jQuery('#button_start').hide();
        jQuery('#span_alert').show();
        return;
    }
    jQuery('#span_alert').hide();
    cache.process_status = status;
    if (cache.process_status === 0) {
        // 设为停止状态
        jQuery('#button_start').show();
        jQuery('#button_pause').hide();
        jQuery('.nav-tabs').show();
    } else {
        // 设为运行状态
        jQuery('#button_start').hide();
        jQuery('#button_pause').show();
        jQuery('.nav-tabs').hide();
    }
}
jQuery(function() {
    function set_box_title(dbhost, dbchar) {
        const dbhost_title = jQuery("[dbhost='" + dbhost + "'] .header font").html();
        const dbchar_title = jQuery("[dbchar='" + dbchar + "'] a").html();
        jQuery('.box-title').html(dbhost_title + '的' + dbchar_title);
    }
    var fileOne;
    const file1 = document.getElementById('file1');
    const span_L1 = document.getElementById('span_L1');
    file1.onchange = function() {
        fileOne = this.files[0];
        if (typeof(fileOne) !== 'object') {
            setStatus(-1);
            return;
        }
        setStatus(0);
        cache.file_size = fileOne.size;
        span_L1.innerHTML = ('文件大小: ' + format_mb(fileOne.size) + ' MB');
        cache.upload_id = (+new Date());
        cache.filename = fileOne.name;

    };
    jQuery('#button_start').click(function() {
        if (typeof(fileOne) !== 'object') {
            alert('请先选择文件');
            return;
        }
        setStatus(1);
        cache.count_all = 0; // 总共
        cache.count_invaild = 0; // 无效数
        cache.count_vaild = 0; // 有效数
        cache.time_start1 = +new Date();
        cache.uploadPosName = 'uploadPos_1_' + fileOne.name + '_' + cache.file_size;
        const uploadPos = CheckProperty(window.localStorage, cache.uploadPosName) ? parseInt(window.localStorage[cache.uploadPosName], 10) : 0;
        upload_start(fileOne, uploadPos);
        return false;
    });
    jQuery('#button_pause').click(function() {
        setStatus(0);
    });
});
//new Vue(vue);
</script><?php }?>
